import java.io.IOException;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.Filter.Chain;

import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.http.server.SimpleServer;
import cn.hutool.http.server.filter.HttpFilter;
import cn.hutool.http.server.filter.SimpleFilter;
import jkoa.core.Context;
import jkoa.core.Log;
import jkoa.core.Request;
import jkoa.core.Response;
import jkoa.middleware.HttpServerMiddleware;
import jkoa.middleware.RouteMiddleware;

public class MyHttpServerMiddleware extends HttpServerMiddleware {

	public MyHttpServerMiddleware(RouteMiddleware route) {
		super(route);
	}

	@Override
	public void init() {

		server = new SimpleServer(8080);

		
		

		
		route.routes.entrySet().stream().forEach(entry -> {
			Log.info("添加路由{}", entry.getKey());
			
			server.addFilter(new HttpFilter() {
				@Override
				public void doFilter(HttpExchange httpExchange, Chain chain) throws IOException {
					filter.doFilter(new HttpServerRequest(httpExchange), new HttpServerResponse(httpExchange), chain);
				}

				@Override
				public void doFilter(HttpServerRequest req, HttpServerResponse res, Chain chain) throws IOException {
					
				}
			});


		});
		
		
		
		
		
		route.routes.entrySet().stream().forEach(entry -> {
			Log.info("添加路由{}", entry.getKey());
			server.addAction(entry.getKey(), (req, res) -> {
				Log.info("执行路由{}", entry.getKey());

//				MyRequest r = new MyRequest(req);
//				MyResponse q = new MyResponse(res);

				MyContext ctx = new MyContext(req,res);

				entry.getValue().handle(ctx);

			});


		});

		server.start();

	}

}
